package com.moli.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.moli.domain.ResponseResult;
import com.moli.domain.entity.User;
import com.moli.domain.entity.UserRole;
import com.moli.domain.vo.PageVo;
import com.moli.domain.vo.UserInfoVo;
import com.moli.domain.vo.UserVo;
import com.moli.enums.AppHttpCodeEnum;
import com.moli.exception.SystemException;
import com.moli.mapper.UserMapper;
import com.moli.service.UserRoleService;
import com.moli.service.UserService;
import com.moli.utils.BeanCopyUtils;
import com.moli.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author xiaolu
 * @Date 2023/6/8
 * @Description 用户服务层实现类
 */

@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

	@Override
	public ResponseResult userInfo() {
		//获取当前用户id
		Long userId = SecurityUtils.getUserId();
		//根据用户id查询用户信息
		User user = getById(userId);
		//封装成UserInfoVo
		UserInfoVo vo = BeanCopyUtils.copyBean(user,UserInfoVo.class);
		return ResponseResult.okResult(vo);
	}

	@Override
	public ResponseResult updateUserInfo(User user) {
		updateById(user);
		return ResponseResult.okResult();
	}

	@Autowired
	private PasswordEncoder passwordEncoder;
	@Override
	public ResponseResult register(User user) {
		//1.对数据进行非空判断
		if(!StringUtils.hasText(user.getUserName())){
			throw new SystemException(AppHttpCodeEnum.USERNAME_NOT_NULL);
		}
		if(!StringUtils.hasText(user.getPassword())){
			throw new SystemException(AppHttpCodeEnum.PASSWORD_NOT_NULL);
		}
		if(!StringUtils.hasText(user.getEmail())){
			throw new SystemException(AppHttpCodeEnum.EMAIL_NOT_NULL);
		}
		if(!StringUtils.hasText(user.getNickName())){
			throw new SystemException(AppHttpCodeEnum.NICKNAME_NOT_NULL);
		}
		//2.对数据进行是否存在的判断
		//用户名已存在的情况
		if(userNameExist(user.getUserName())){
			throw new SystemException(AppHttpCodeEnum.USERNAME_EXIST);
		}
		//昵称已存在的情况
		if(nickNameExist(user.getNickName())){
			throw new SystemException(AppHttpCodeEnum.NICKNAME_EXIST);
		}
		//...
		//3.对密码进行加密
		String encodePassword = passwordEncoder.encode(user.getPassword());
		user.setPassword(encodePassword);
		//4.存入数据库（MP自带save方法）
		save(user);
		return ResponseResult.okResult();
	}

	@Override
	public ResponseResult selectUserPage(User user, Integer pageNum, Integer pageSize) {
		LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper();

		queryWrapper.like(StringUtils.hasText(user.getUserName()),User::getUserName,user.getUserName());
		queryWrapper.eq(StringUtils.hasText(user.getStatus()),User::getStatus,user.getStatus());
		queryWrapper.eq(StringUtils.hasText(user.getPhonenumber()),User::getPhonenumber,user.getPhonenumber());

		Page<User> page = new Page<>();
		page.setCurrent(pageNum);
		page.setSize(pageSize);
		page(page,queryWrapper);

		//转换成VO
		List<User> users = page.getRecords();
		List<UserVo> userVoList = users.stream()
				.map(u -> BeanCopyUtils.copyBean(u, UserVo.class))
				.collect(Collectors.toList());
		PageVo pageVo = new PageVo();
		pageVo.setTotal(page.getTotal());
		pageVo.setRows(userVoList);
		return ResponseResult.okResult(pageVo);
	}

	@Override
	public boolean checkUserNameUnique(String userName) {
		return count(Wrappers.<User>lambdaQuery().eq(User::getUserName,userName))==0;
	}

	@Override
	public boolean checkPhoneUnique(User user) {
		return count(Wrappers.<User>lambdaQuery().eq(User::getPhonenumber,user.getPhonenumber()))==0;
	}

	@Override
	public boolean checkEmailUnique(User user) {
		return count(Wrappers.<User>lambdaQuery().eq(User::getEmail,user.getEmail()))==0;
	}

	@Override
	@Transactional
	public ResponseResult addUser(User user) {
		//密码加密处理
		user.setPassword(passwordEncoder.encode(user.getPassword()));
		save(user);

		if(user.getRoleIds()!=null&&user.getRoleIds().length>0){
			insertUserRole(user);
		}
		return ResponseResult.okResult();
	}

	@Override
	@Transactional
	public void updateUser(User user) {
		// 删除用户与角色关联
		LambdaQueryWrapper<UserRole> userRoleUpdateWrapper = new LambdaQueryWrapper<>();
		userRoleUpdateWrapper.eq(UserRole::getUserId,user.getId());
		userRoleService.remove(userRoleUpdateWrapper);

		// 新增用户与角色管理
		insertUserRole(user);
		// 更新用户信息
		updateById(user);
	}

	@Autowired
	private UserRoleService userRoleService;

	private void insertUserRole(User user) {
		List<UserRole> sysUserRoles = Arrays.stream(user.getRoleIds())
				.map(roleId -> new UserRole(user.getId(), roleId)).collect(Collectors.toList());
		userRoleService.saveBatch(sysUserRoles);
	}

	//昵称的非空判断
	private boolean nickNameExist(String nickName) {
		LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(User::getNickName,nickName);
		return count(queryWrapper)>0;
	}

	//用户名的非空判断
	private boolean userNameExist(String userName) {
		LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(User::getUserName,userName);
		return count(queryWrapper)>0;  //存在 相当于返回true
	}

	//邮箱的非空判断
	//密码的非空判断
}
